<template>
  <div class="card flex-1">
    <h2 class="text-lg font-bold">招商引资形成实物量年度目标完成率</h2>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 p-4">
      <div class="bg-white rounded-lg shadow p-4 flex flex-col items-center justify-center">
        <p class="text-sm text-gray-500 mb-1">当前完成量</p>
        <p class="text-2xl font-bold text-primary">
          {{ resList[props.yearStr].completedAmount }}<span class="unit">亿元</span>
        </p>
      </div>
      <div class="bg-white rounded-lg shadow p-4 flex flex-col items-center justify-center">
        <p class="text-sm text-gray-500 mb-1">年度目标</p>
        <p class="text-2xl font-bold text-gray-700">
          {{ resList[props.yearStr].targetAmount }}<span class="unit">亿元</span>
        </p>
      </div>
      <div class="bg-white rounded-lg shadow p-4 flex flex-col items-center justify-center">
        <p class="text-sm text-gray-500 mb-1">完成率</p>
        <p class="text-2xl font-bold text-{{ progressColor }}">
          {{ resList[props.yearStr].completionRate }}<span class="unit">%</span>
        </p>
      </div>
    </div>
    <div class="p-4">
      <div class="w-full h-64 flex items-center justify-center">
        <canvas id="progressChart"></canvas>
      </div>
    </div>
    <div class="px-4 pb-4">
      <div class="flex justify-between text-sm">
        <div class="flex items-center">
          <span class="inline-block w-3 h-3 rounded-full bg-[#8DBC82] mr-1"></span>
          <span>已完成</span>
        </div>
        <div class="flex items-center">
          <span class="inline-block w-3 h-3 rounded-full bg-[#E5E7EB] mr-1"></span>
          <span>未完成</span>
        </div>
        <div class="flex items-center">
          <span class="inline-block w-3 h-3 rounded-full bg-[#EA3921] mr-1"></span>
          <span>预警线(75%)</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Chart from 'chart.js/auto'
import { ref, defineProps, onMounted, watch, onUnmounted } from 'vue'

const props = defineProps({
  yearStr: String,
})

// 产业占比数据
const resList = ref({
  2024: {
    targetAmount: 2556,
    completedAmount: 2885,
    completionRate: ((2885 / 2556) * 100).toFixed(1), // 完成率
  },
  2023: {
    targetAmount: 2998,
    completedAmount: 1998,
    completionRate: ((1998 / 2998) * 100).toFixed(1), // 完成率
  },
  2022: {
    targetAmount: 3556,
    completedAmount: 2881,
    completionRate: ((2881 / 3556) * 100).toFixed(1), // 完成率
  },
  2021: {
    targetAmount: 2005,
    completedAmount: 1855,
    completionRate: ((1855 / 2005) * 100).toFixed(1), // 完成率
  },
  2020: {
    targetAmount: 3000, // 年度目标(亿元)
    completedAmount: 1500, // 当前完成量(亿元)
    completionRate: ((1500 / 3000) * 100).toFixed(1), // 完成率为50%
  },
})

// 图表实例引用
const progressChart = ref(null)
// 根据完成率确定颜色
const progressColor = ref('primary')
// 控制预警线显示
const showWarningLine = ref(false)

// 初始化图表
const initChart = () => {
  // 销毁已存在的图表实例
  if (progressChart.value) {
    progressChart.value.destroy()
  }

  const ctx = document.getElementById('progressChart').getContext('2d')

  // 获取当前年份数据
  const currentYearData = resList.value[props.yearStr]
  const actualCompletionRate = parseFloat(currentYearData.completionRate)

  // 处理超额完成情况（完成率超过100%时图表显示为100%）
  let displayCompletionRate = Math.min(actualCompletionRate, 100)

  // 更新颜色和预警线显示状态
  if (actualCompletionRate < 60) {
    progressColor.value = 'danger'
    showWarningLine.value = true // 低于60%显示预警线
  } else if (actualCompletionRate < 75) {
    progressColor.value = 'warning'
    showWarningLine.value = true // 60%-75%之间显示预警线
  } else {
    progressColor.value = 'success'
    showWarningLine.value = false // 大于等于75%不显示预警线
  }

  // 创建新图表实例
  progressChart.value = new Chart(ctx, {
    type: 'doughnut',
    data: {
      datasets: [
        {
          data: [displayCompletionRate, 100 - displayCompletionRate],
          backgroundColor: ['#8DBC82', '#E5E7EB'],
          borderWidth: 0,
          cutout: '75%',
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false,
        },
        tooltip: {
          enabled: true,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          titleColor: '#333',
          bodyColor: '#666',
          borderColor: 'rgba(220, 220, 220, 1)',
          borderWidth: 1,
          padding: 12,
          boxPadding: 6,
          usePointStyle: true,
          pointStyle: 'circle',
          callbacks: {
            label: function (context) {
              const label = context.dataIndex === 0 ? '已完成' : '未完成'
              const value = context.raw

              // 超额完成时显示实际百分比
              if (context.dataIndex === 0 && actualCompletionRate > 100) {
                return `已完成: ${actualCompletionRate.toFixed(1)}% (超额${(actualCompletionRate - 100).toFixed(1)}%)`
              }

              return `${label}: ${value.toFixed(1)}%`
            },
            title: function (tooltipItems) {
              return `${props.yearStr}年完成率`
            },
          },
        },
      },
      animation: {
        animateRotate: true,
        animateScale: true,
      },
    },
    plugins: [
      {
        id: 'centerText',
        beforeDraw: function (chart) {
          const width = chart.width
          const height = chart.height
          const ctx = chart.ctx

          ctx.restore()
          ctx.font = 'bold 24px Arial'
          ctx.textBaseline = 'middle'
          ctx.fillStyle = '#333'

          const text = `${currentYearData.completionRate}%`
          const textX = Math.round((width - ctx.measureText(text).width) / 2)
          const textY = height / 2

          ctx.fillText(text, textX, textY)

          ctx.font = '14px Arial'
          ctx.fillStyle = '#666'

          const subText = '目标完成率'
          const subTextX = Math.round((width - ctx.measureText(subText).width) / 2)
          const subTextY = height / 2 + 25

          ctx.fillText(subText, subTextX, subTextY)
          ctx.save()
        },
      },
      {
        id: 'warningLine',
        afterDraw: function (chart) {
          if (showWarningLine.value) {
            const width = chart.width
            const height = chart.height
            const ctx = chart.ctx
            const radius = ((chart.chartArea || {}).width / 2) * 0.75
            const centerX = (chart.chartArea || {}).left + radius
            const centerY = (chart.chartArea || {}).top + radius

            ctx.restore()
            ctx.beginPath()
            ctx.arc(centerX, centerY, radius, 0, Math.PI * 2 * 0.75)
            ctx.lineWidth = 3
            ctx.strokeStyle = '#EA3921'
            ctx.setLineDash([5, 5])
            ctx.stroke()
            ctx.save()
          }
        },
      },
    ],
  })
}

onMounted(() => {
  initChart()
})

// 监听yearStr变化
watch(
  () => props.yearStr,
  (newYear, oldYear) => {
    if (newYear && resList.value[newYear]) {
      initChart()
    }
  },
)

// 组件卸载时销毁图表实例
onUnmounted(() => {
  if (progressChart.value) {
    progressChart.value.destroy()
  }
})
</script>

<style scoped>
/* 颜色变量 */
:root {
  --primary: #165dff;
  --success: #00b42a;
  --warning: #ff7d00;
  --danger: #f53f3f;
}

/* 文字颜色类 */
.text-primary {
  color: var(--primary);
}
.text-success {
  color: var(--success);
}
.text-warning {
  color: var(--warning);
}
.text-danger {
  color: var(--danger);
}

/* 卡片样式 */
</style>
